var tgd = tgd || {};
tgd.Contests = tgd.Contests || {};
tgd.Contests.Darts = tgd.Contests.Darts || {};
tgd.Contests.Darts.Views = tgd.Contests.Darts.Views || {};

/*
 * BestScores CLASS
 *
 * 3 to 6 darts (D)
 * [1] to [(7 - D) * 10] regions (R)
 */
tgd.Contests.Darts.Views.BestScores = function (canvas) {
	this._canvas = canvas;
	this._maxScores = [];
	this._table = null;

	var tempRow = null;

	for (var i = 3; i < 7; ++i) {
		this._maxScores[i] = [];
		for (var j = 1; j <= (7 - i) * 10; ++j) {
			this._maxScores[i][j] = { Solution: null, Value: 0, TimeFound: null };
		}
	}

    this._table = document.createElement("table");
	this._table.createTHead();
	tempRow = this._table.tHead.insertRow(0);
	for (var i = 0; i < 5; ++i, this._table.tHead.rows[0].appendChild(document.createElement("th")));
	tempRow.cells[0].innerHTML = "#Darts";
	tempRow.cells[1].innerHTML = "#Regions";
	tempRow.cells[2].innerHTML = "Score";
	tempRow.cells[3].innerHTML = "Time";
	tempRow.cells[4].innerHTML = "Solution";
	
    for (var i = 0; i < 100; ++i) {
        tempRow = this._table.tBodies[0].insertRow(i);
		for (var j = 0; j < 5; tempRow.insertCell(j++));
    }

    this._canvas.appendChild(this._table);

	if (tgd.Contests.Darts.Views.BestScores._initialized === undefined) {

		tgd.Contests.Darts.Views.BestScores.prototype.onUpdate = function(s) {
			var temp = null;
			var currentMax = this._maxScores[s.getNumDarts()][s.getNumRegions()];
			if ((temp = s.getSmallestScoreUnattainable()) > currentMax.Value) {
				currentMax.Value = temp;
				currentMax.Solution = s;
				currentMax.TimeFound = new Date();

				//todo:  this is ugly, i know
				var idx = 0;
				switch (currentMax.Solution.getNumDarts()) {
					case 3: idx = 0; break;
					case 4: idx = 4; break;
					case 5: idx = 7; break;
					case 6: idx = 9; break;
					default: break;
				}
				var row = this._table.rows[idx * 10 + currentMax.Solution.getNumRegions()]
				row.cells[0].innerHTML = currentMax.Solution.getNumDarts();
				row.cells[1].innerHTML = currentMax.Solution.getNumRegions();
				row.cells[2].innerHTML = currentMax.Value;
				row.cells[3].innerHTML = currentMax.TimeFound;
				row.cells[4].innerHTML = currentMax.Solution;

				//todo: maybe use a class instead of hardcoding colors?
				row.style.backgroundColor = "#0f0";
				setTimeout(function() { row.style.backgroundColor = ""; }, 1024);
			}
		}

		tgd.Contests.Darts.Views.BestScores._initialized = true;
	}
};